<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import {
  getDishPage,
  reqDeleteDish,
  reqAddDish,
  reqUpdateDish,
  reqGetCategoryList,
} from '@/api/product/food'
import type { Action, UploadProps } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
//对话框是否显示
let dialogFormVisible = ref<boolean>(false)
//当前页码
let pageNo = ref<number>(1)
//每页条数
let limit = ref<number>(10)
// 存储一下已有品牌数据的总数
let total = ref<number>(0)
//存储数据
let dishArr = ref<any>([])
//存储菜品分类数据
let dishCategoryArr = ref<any>([])
//数据类型
let dishParams = reactive<any>({
  categoryId: '',
  categoryName: '',
  code: '', //商品码
  createTime: '',
  createUser: '',
  description: '',
  flavors: [],
  id: '',
  image: '',
  name: '',
  price: '',
  sort: '',
  status: '1',
  updateTime: '',
  updateUser: '',
})
let flavor = reactive<any>({
  name: '',
  value: [],
})
// 获取已有品牌的接口封装为一个函数
const getDish = async () => {
  let result = await getDishPage(pageNo.value, limit.value)
  console.log(result)
  if (result.code == 1) {
    //存储总个数
    total.value = result.data.total
    dishArr.value = result.data.records
    console.log( dishArr.value[5].image)
  }
}
//分页器页码发生变化时候触发
const changePageNo = () => {
  //当前页码发生变化的时候，再次发请求，获取数据
  getDish()
}
//当下拉菜单发生变化的时候，会触发此方法
const sizeChange = () => {
  pageNo.value = 1
  getDish()
}
//发送请求，组件一挂载
onMounted(() => {
  getDish()
})
//添加菜品的按钮点击回调
const addDishButton = () => {
  dialogFormVisible.value = true
  clearDish()
  getDishCategoryList()
}
//清空方法数据
const clearDish = () => {
  dishParams.categoryId = ''
  dishParams.categoryName = ''
  dishParams.code = '' //商品码
  dishParams.createTime = ''
  dishParams.createUser = ''
  dishParams.description = ''
  dishParams.flavors = []
  dishParams.id = ''
  dishParams.image = ''
  dishParams.name = ''
  dishParams.price = ''
  dishParams.sort = ''
  dishParams.status = '1'
  dishParams.updateTime = ''
  dishParams.updateUser = ''
}
//获取分类数据的方法
const getDishCategoryList = async () => {
  let result = await reqGetCategoryList()
  //console.log(result)
  dishCategoryArr.value = result.data
}
//处理一下数据

//图片上传的方法，之前的钩子
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  //约束文件的类型和大小
  if (
    rawFile.type != 'image/jpeg' &&
    rawFile.type != 'image/png' &&
    rawFile.type != 'image/gif'
  ) {
    ElMessage.error('Avatar picture must be JPG ,PNG, GIF!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 4) {
    ElMessage.error('Avatar picture size can not exceed 4MB!')
    return false
  }
  return true
}
//图片上传成功钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile,
) => {
  dishParams.image = 'http://localhost:8080/image/' + response.data
}
//是否删除的弹出确定框
const openDel = (row: any) => {
  let message = '是否删除'
  ElMessageBox.alert(message, row.name, {
    // if you want to disable its autofocus
    // autofocus: false,
    confirmButtonText: '确定',
    callback: (action: Action) => {
      if (action == 'cancel') {
        ElMessage({
          type: 'info',
          message: '取消',
        })
      } else {
        //调用修改状态的方法
        deleteCategory(row)
      }
    },
  })
}
//删除方法
const deleteCategory = async (row: any) => {
  console.log('del category')
  let result = await reqDeleteDish(row.id)
  if (result.code == 1) {
    //弹出提示
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    //发起请求
    getDish()
  } else {
    //失败
    ElMessage({
      type: 'error',
      message: result.msg,
    })
  }
}
//新增方法
const confirm = async () => {
  if (dishParams.createUser == '') {
    dishParams.createUser = localStorage.getItem('token')
  }
  dishParams.updateUser = localStorage.getItem('token')
  dishParams.price = dishParams.price * 100
  // 判断是否是新增还是 修改
  if (dishParams.updateTime == '') {
    console.log('add ')
    let result = await reqAddDish(dishParams)
    if (result.code == 1) {
      //添加用户成功
      dialogFormVisible.value = false
      //弹出提示
      ElMessage({
        type: 'success',
        message: '添加成功',
      })
      //发起请求
      getDish()
      //收集数据清空
    } else {
      //失败
      ElMessage({
        type: 'error',
        message: result.msg,
      })
      dialogFormVisible.value = false
    }
  } else {
    console.log('update')
    let result = await reqUpdateDish(dishParams)
    if (result.code == 1) {
      //添加用户成功
      dialogFormVisible.value = false
      //弹出提示
      ElMessage({
        type: 'success',
        message: '更新成功',
      })
      //发起请求
      getDish()
    } else {
      //失败
      ElMessage({
        type: 'error',
        message: result.msg,
      })
      dialogFormVisible.value = false
    }
  }
}
</script>

<template>
  <div class="-container">
    <el-card
      shadow="always"
      :body-style="{ padding: '20px' }"
      style="margin: 10px 0px"
    >
      <!-- card body -->
      <div
        style="
          display: flex;
          justify-content: space-between;
          align-items: center;
        "
      >
        <el-input
          placeholder="请输入菜品名称"
          size="normal"
          clearable
          prefix-icon="Search"
          style="width: 200px"
        ></el-input>
        <div>
          <span style="margin: 0px 5px">批量删除</span>
          <span style="margin: 0px 5px">批量启售</span>
          <span style="margin: 0px 5px">批量禁售</span>
        </div>
      </div>
    </el-card>

    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <!-- card body -->
      <!-- 顶部的设置按钮 -->
      <el-button
        type="primary"
        size="default"
        icon="Plus"
        @click="addDishButton"
      >
        添加菜品
      </el-button>
      <!-- 表格组件用户展示已经有的菜品 -->
      <el-table :data="dishArr" style="margin: 20px 0px">
        <el-table-column type="selection" width="50" />
        <el-table-column label="菜品名称" prop="name"></el-table-column>
        <el-table-column label="图片">
          <template #="{ row, $index }">
            <image :src="row.image" style="width: 100px; height: 100px"></image>
          </template>
        </el-table-column>
        <el-table-column
          label="菜品分类"
          prop="categoryName"
          width="100"
        ></el-table-column>
        <el-table-column label="售价" width="100">
          <template #="{ row, $index }">
            <text>￥{{ row.price / 100 }}</text>
          </template>
        </el-table-column>
        <el-table-column label="售卖状态" prop="status" width="100">
          <template #="{ row, $index }">
            <text>{{ row.status == 1 ? '启用' : '禁用' }}</text>
          </template>
        </el-table-column>
        <el-table-column label="最后操作时间">
          <template #="{ row, $index }">
            <text style="color: rgb(108, 200, 239)">{{ row.updateTime }}</text>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #="{ row, $index }">
            <el-button type="primary" size="small" icon="Edit" circle />
            <el-button type="primary" size="small" circle>停售</el-button>
            <el-button
              type="danger"
              size="small"
              icon="Delete"
              circle
              @click="openDel(row)"
            />
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器组件
       v-model:current-page :设置当前的分页器页码
       v-model:page-size : 展示条数每一页
       :page-sizes :设置下拉框的选择条数
       layout ：分页器的六个子组件的位置调整
      -->
      <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="sizeChange"
        @current-change="changePageNo"
      />
    </el-card>
    <!-- 对话框 -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="dishParams.name == '' ? '新增菜品' : '修改菜品'"
    >
      <el-form
        :inline="false"
        size="normal"
        label-width="20%"
        :model="dishParams"
        :rules="rules"
      >
        <el-form-item label="菜品名称" prop="name">
          <el-input
            v-model="dishParams.name"
            placeholder="输入名称"
            size="normal"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input
            v-model="dishParams.price"
            placeholder="输入价格"
            size="normal"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="菜品分类">
          <el-select
            v-model="dishParams.categoryId"
            placeholder="请选择你所属菜系"
          >
            <el-option
              v-for="(item, index) in dishCategoryArr"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="菜品图片">
          <!-- upload： url图片地址 -->
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8080/common/upload"
            :show-file-list="true"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="dishParams.image"
              :src="dishParams.image"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="菜品描述" prop="description">
          <el-input
            v-model="dishParams.description"
            placeholder="不超过50个字"
            size="normal"
            clearable
            type="textarea"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="confirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
